import { ElMessage } from 'element-plus';
import { useMemberLevelApi, useMemberRecommendApi } from '/@/api/member';
import { useCustomerApi } from '/@/api/customer';
import { useProductApi } from '/@/api/product';

const { getMemberLevelList, delMemberLevel } = useMemberLevelApi();
const { getMemberRecommendList, updateMemberRecommend } = useMemberRecommendApi();
const { getCustomerList } = useCustomerApi();
const { getProdSkuList } = useProductApi();

export const useInit = () => {
	const memberList = ref([]);
	const productList = ref([]);
	const tableData = ref([]);
	const tableDataRecommend = ref([]);

	function page() {
		return {
			current: 1,
			pageSize: 10,
			total: 0,
		};
	}

	const levelPage = ref(page());

	const initMemberLevel = async () => {
		let res = await getMemberLevelList(levelPage.value);
		if (res.code == 200) {
			const { data, total } = res.data;
			tableData.value = data;
			levelPage.value.total = total;
		}
	};

	const initMemberRecommend = async () => {
		let res = await getMemberRecommendList({});
		if (res.code == 200) {
			const { data } = res;
			tableDataRecommend.value = data;
		}
	};

	const initCustomerList = async () => {
		let params = {
			current: 1,
			isVip: 1,
			pageSize: 999999,
		};
		const res = await getCustomerList(params);
		if (res.code === 200) {
			memberList.value = res.data.data;
		}
	};
	const getProductList = async () => {
		let page = {
			current: 1,
			pageSize: 999999,
		};
		let res = await getProdSkuList({ ...page.value });
		if (res.code == 200) {
			console.log(res);
			productList.value = res.data.data;
		}
	};

	return {
		initMemberLevel,
		initMemberRecommend,
		page,
		initCustomerList,
		getProductList,
		tableData,
		productList,
		tableDataRecommend,
		levelPage,
		memberList,
	};
};

export const useAdd = (addLevelRef) => {
	const onOpenAddLevel = (row) => {
		addLevelRef.value.openDialog(row);
	};

	return {
		onOpenAddLevel,
	};
};

export const useEdit = (editLevelRef) => {
	const onOpenEditLevel = (row) => {
		editLevelRef.value.openDialog(row);
	};

	const onUpdateRecommend = async ({ id, commission }) => {
		let res = await updateMemberRecommend({ id, commission });
		if (res.code == 200) {
			ElMessage({
				type: 'success',
				message: '保存成功！',
			});
		}
	};

	return {
		onOpenEditLevel,
		onUpdateRecommend,
	};
};

export const useDel = (initMemberLevel) => {
	const onDeleteLevel = async (id) => {
		let res = await delMemberLevel({ id });
		if (res.code === 200) {
			initMemberLevel();
			ElMessage({
				type: 'success',
				message: '删除成功！',
			});
		} else {
			ElMessage({
				type: 'error',
				message: '删除失败！',
			});
		}
	};

	return {
		onDeleteLevel,
	};
};
